package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jinpei
 * @version v1.0
 * @date 2019/5/15 17:07
 * @description TODO
 **/
@Service
@Slf4j
public class PageService {

    @Autowired
    private ItemClient itemClient;

    public Map<String, Object> loadItemData(Long spuId) {
        // 查询spu
        SpuDTO spu = itemClient.querySpuById(spuId);
        // 查询分类集合
        List<CategoryDTO> categories = itemClient.queryCategoryByIds(spu.getCategoryIds());
        // 查询品牌
        BrandDTO brand = itemClient.queryBrandById(spu.getBrandId());
        // 查询规格
        List<SpecGroupDTO> specs = itemClient.querySpecsByCid(spu.getCid3());

        // 封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("categories", categories);
        map.put("brand", brand);
        map.put("spuName", spu.getName());
        map.put("subTitle", spu.getSubTitle());
        map.put("skus", spu.getSkus());
        map.put("detail", spu.getSpuDetail());
        map.put("specs", specs);
        return map;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;

    private static final String BASE_DIR = "D:\\nginx-1.14.0\\html\\item";
    public void creatItemHtml(Long spuId) {
        // 准备上下文，上下文中必须有模板中需要的模型数据
        Context context = new Context();
        context.setVariables(loadItemData(spuId));
        // 准备目标文件
        File file = new File(BASE_DIR, spuId + ".html");
        // 输出流
        try (Writer writer = new PrintWriter(file, "UTF-8")) {
            templateEngine.process("item", context, writer);
        } catch (Exception e) {
            log.error("【静态页服务】创建静态页面失败，商品id：{}", spuId, e);
            throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
        }
    }

    public void deleteItemHtml(Long spuId) {
        // 准备目标文件
        File file = new File(BASE_DIR, spuId + ".html");
        // 删除
        if (file.exists()) {
            boolean result = file.delete();
            if (!result) {
                log.error("【静态页服务】静态页删除失败，商品id：{}", spuId);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
            }
        }
    }
}
